package com.lx.javasunmmrize.prototype;

import java.io.*;

/**
 * @Description 克隆问题:如果要创建多个和该对象属性相同的对象
 * 浅拷贝: 实现接口，重写clone()方法，达到能通过拷贝属性创建新的对象的目的
 * <p>
 * 深拷贝：实现方式
 * 1.重写clone()方法
 * 2.序列化
 * @Author lx
 * @Date 2021/2/26 23:30
 **/
public class Cat2 implements Cloneable, Serializable {

    private String name;
    private String color;

    private PeopleTarget people;

    public PeopleTarget getPeople() {
        return people;
    }

    public void setPeople(PeopleTarget people) {
        this.people = people;
    }

    public Cat2(String name, String color) {
        super();
        this.name = name;
        this.color = color;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return "Cat2{" +
                "name='" + name + '\'' +
                ", color='" + color + '\'' +
                '}';
    }

    //重写clone()
    protected Object clone() throws CloneNotSupportedException {
        Object cat = null;

        //1.对基础属性及String进行复制
        cat = (Cat2) super.clone();
        Cat2 cat2 = (Cat2) cat;
        //对引用类型的复制
        cat2.people = (PeopleTarget) people.clone();
        return cat2;
    }


    //深拷贝,序列化
    public  Object deepClone(){

        //创建流对象
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try {
            //序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);

            //将当前这个对象按对象流方式输出
            oos.writeObject(this);

            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);

            Cat2 cat = (Cat2) ois.readObject();

            return cat;


        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            //关闭对应流
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }


}
